package tjs.study.notes.dotest.jdk.thread.reentrantLock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: tjs
 * @desc:
 * @author: tjs
 * @create: 2019-10-13 22:42
 */
public class DoTestOfReentLock {
    // volatile并没有解决原子性
    public static volatile Integer a = 0;

    private static final AtomicInteger at = new AtomicInteger();

    public static ReentrantLock lock = new ReentrantLock();

    public static ExecutorService executorService = Executors.newFixedThreadPool(20);


    public static void add(Integer i) {
        a++;
    }

    public static void testLock() {
        System.out.println(Thread.currentThread().getName() + "获取锁准备");
//        lock.lock();
        try {
            lock.lockInterruptibly();
        } catch (InterruptedException e) {
            // 只有调用了interrupt方法的才会抛出异常中断此操作
            System.out.println(Thread.currentThread().getName() + "获取锁失败");
            e.printStackTrace();
            return;
        }
        System.out.println(Thread.currentThread().getName() + "获取锁成功");
        try {
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            for (int ii = 0; ii < 100; ii++) {

                // 停一会，不然看不出效果
                a++;
//                Thread.currentThread().sleep(200);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 如果不手动释放，则会一直拥有着锁
            lock.unlock();
        }
    }


    public static void main(String[] args) throws InterruptedException {

        Thread[] threads = new Thread[3];
        for (int i = 0; i < 3; i++) {
            threads[i] = new Thread(new Runnable() {
                //                @Override
                public void run() {
                    testLock();
                }
            });
        }

        for (Thread thread : threads) {
            synchronized (Thread.class){
                thread.start();
            }
        }

        Thread.currentThread().sleep(1000);
        threads[2].interrupt();

//        Thread.currentThread().sleep(10000);
//        new Thread(() -> {
//            while (true) {
//                // 最终结果并不等于1000  这个线程读取count的时候，上一个线程还没把更新的count值写入内存
//                System.out.println(a);
//                try {
//                    Thread.currentThread().sleep(2000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
////                System.out.println("at" + at.get());
//            }
//        }).start();
    }
}